/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
/**
 * Created by oj on 2018/3/25
 */

import $ from 'jquery';

import Vue from 'vue';
import UedcLogin from '@uedc/login';
import '@uedc/login/dist/theme/cloud.css';
import {
    setStorage
} from 'src/util/local_storage';
import {
    USER_ID,
    USER_ROLE
} from 'src/home/mod_common/const';

// import urlAdapter from 'src/home/mod_common/url_adapter';

// import { getEncryptor } from 'src/util/rsa';
import usernameValidator from 'src/util/validator/username_validator';
import './index.less';

const LOGIN_URL = 'auth/v1/login';

const CODE_URL = 'auth/v1/kaptcha';


import _updateUserPassword from './update_pwd';
import IntervalTask from 'src/util/interval_task';

// import { isBrowserVisibility } from 'src/util/check_browser';

// 需传入后台给的公钥等信息, 用于加密密码
export default function initLoginPage (info) {

    const INPUT_NAME_USERNAME = 'username';
    const INPUT_NAME_PASSWORD = 'password';

    let vm = new Vue();
    let isChangingPassword = false;

    // let encrypt = getEncryptor(info.modulus, info.publicKey);

    UedcLogin.init(document.body, {
        type: 'signin',

        debug: {
            enable: process.env.NODE_ENV === 'development',
            product: 'RI',
            project: 'AI',
            version: '4.0.0'
        },

        gcs: [{
            name: _('GeniusAI算法研发平台'),
            content: _('GeniusAI智能平台，提供简单、高效、智能和安全的AI平台'),
            animation: true,
            more: {
                enable: false,
                text: _('了解更多'),
                href: 'https://www.baidu.com'
            }
        }],

        product: {
            name: _('GeniusAI算法研发平台'),
            logoCls: 'acmp-logo',
            help: {
                'i18n': {
                    enable: false // 关闭中英文切换
                }
            }
        },

        accountLogin: {
            enable: true,
            items: [{
                    name: INPUT_NAME_USERNAME,
                    type: 'text',
                    label: _('用户名'),
                    placeHolder: _('请输入你的用户名')
                },
                {
                    name: INPUT_NAME_PASSWORD,
                    type: 'password',
                    label: _('密码'),
                    placeHolder: _('请输入你的密码')
                },
                {
                    name: 'verifyCode',
                    type: 'captcha',
                    visibility: true,
                    label: _('验证码'),
                    placeHolder: _('请按右图输入验证码'),
                    url: CODE_URL,
                    onLoad () {
                        let captchaEle = document.getElementsByClassName('uedc-ppkg-login_form-item-captcha')[0];
                        Vue.prototype.$unmask(captchaEle);
                        if (vm.intervalTask) {
                            vm.intervalTask.stop();
                            vm.intervalTask.start();
                        }
                    }
                }
            ]
        },

        signup: {
            enable: false // 去掉"注册社区账号"
        },

        policy: {
            enable: false // 去掉"隐私政策"勾选框
        },

        /* eslint-disable */
        async onSubmit(formValue) {
            if (isChangingPassword) {
                return;
            }
            let formdata = {
                username:formValue.username,
                password:formValue.password,
                scope:'all',
                grantType:'password',
                code: formValue.verifyCode
            };
            let jsonData = await vm.$ajax.post(LOGIN_URL, formdata);
            let {success, msg,data} = jsonData;
            if (success) {
                if (data.isFirstLogin) {
                    isChangingPassword = true;
                    formValue.userId = data.userId;
                    _updateUserPassword(formValue, data.token, {
                        successCB: () => {
                            isChangingPassword = false;
                        }
                    });
                    // 修改完刷新验证码
                    UedcLogin.reloadCaptcha();
                }else{
                    data.userName = formValue.username;
                    //userId
                    setStorage(USER_ID, data && data.userId);
                    //是否为管理员
                    setStorage(USER_ROLE, data && data.role);
                    setStorage('token', data && data.s3Token);
                    location.href = `./index.html${location.search}`;
                }
            }else{
                // 修改完刷新验证码
                $('.uedc-ppkg-login_product-captcha-input').val('');
                UedcLogin.reloadCaptcha();
                UedcLogin.setError(msg || _('登录失败'));
            }
        }
        /* eslint-enable */
    });

    // 处理自定义的登录校验
    function validator (handler, formSelector) {
        if (!handler) {
            return;
        }

        let $$ = (function (context) {
            return function (selector) {
                return $(selector, context);
            };
        })($(formSelector, document.body));

        $$('input').on('input', function (event) {
            let input = this;
            let {
                name,
                value
            } = input;
            handler[name] && typeof handler[name] === 'function' && handler[name].call(input, value, event);
        });
    }

    validator({
        [INPUT_NAME_USERNAME]: (value) => {
            let errMsg = usernameValidator(value, null);
            if (errMsg && typeof errMsg !== 'boolean') {
                return UedcLogin.setError(errMsg);
            }
        }
    }, '.uedc-ppkg-login_product-form');

    // UedcLogin.setBrowserVisibility(!isBrowserVisibility ? true : false);

    if (info.version) {
        UedcLogin.setVersion('AI ' + info.version);
    }

    vm.intervalTask = new IntervalTask({
        fn: () => {
            UedcLogin.reloadCaptcha();
        },

        // eslint-disable-next-line no-magic-numbers
        interval: 1000 * 60 * 5,    // 5分钟
        autoStart: true,
        skipFirst: true
    });
};
